package cn.tedu.charging.order.config;

import cn.tedu.charging.order.emqx.MqttConsumer;
import cn.tedu.charging.order.emqx.MqttContext;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.UUID;

/**
 * 在容器中创建mqtt客户端 连接 1883 emqx
 * 实现 生产 消费
 */
@Configuration
@Slf4j
public class MqttClientConfiguration {
    //charging.emqx.address
    @Value("${charging.emqx.address}")
    private String address;
    //charging.emqx.username
    @Value("${charging.emqx.username}")
    private String username;
    //charging.emqx.password
    @Value("${charging.emqx.password}")
    private String password;
    @Autowired
    private MqttContext mqttContext;
   /* @Autowired
    private OrderMapper orderMapper;*/
    @Bean
    public MqttClient mqttClient(){
        MqttClient mqttClient = null;
        try{
            mqttClient=
            new MqttClient(address,"charging-client"+ UUID.randomUUID().toString(),
                    new MemoryPersistence());
            MqttConnectOptions options=new MqttConnectOptions();
            options.setUserName(username);
            options.setPassword(password.toCharArray());
            //作为了解
            //options.setCleanSession(true);
            //options.setKeepAliveInterval(30);
            //options.setConnectionTimeout(30);
            //options.setAutomaticReconnect(true);
            //通过选项建立client客户端和服务端连接
            //如果客户端只是生产消息,现在的参数就足够了,但是如果客户端负责消费监听 需要一个consumer回调对象
            mqttClient.setCallback(new MqttConsumer(mqttClient,mqttContext));
            mqttClient.connect(options);
        }catch (Exception e){
            log.error("创建mqtt客户端失败",e);
        }
        return mqttClient;
    }
}
